<template>
    <div v-loading="fullLoading">
        <div>
            <img :src='src' style="width: 400px;height: 300px;margin-right: 5px;margin-left: 5px;border-radius: 40px" v-if="chouse==1">
            <img :src='src1' style="width: 400px;height: 300px;margin-right: 5px;margin-left: 5px;border-radius: 40px" v-if="chouse==2">
        </div>
        <el-form>
            <el-form-item>
                <el-upload class="avatar-uploader"
                        :on-success="handleAvatarSuccess"
                        :action="uploadUrl"
                        :before-upload="beforeAvatarUpload"
                        :on-error="handleAvatarError"
                        :show-file-list="false"
                        :data="{id:id}"
                        >
                    <el-button size="small"
                            type="primary" icon="el-icon-upload">点击上传</el-button>
                </el-upload>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
export default {
    data(){
        return{
            src1:'',//由于子组件不能改变父组件传入参数,方便上传完成后浏览图片
            chouse:1,//用于判断当前显示图片是上传完成后图片还是初始图片
            fullLoading:false,
        }
        
    },
    mounted:function(){
      console.log(this.src)
    },
    //接收父组件传入的参数,包括id和图片src,id主要用于确定图片对应关系
    props:{
        id:{
            type:Number,
            required:true
        },
        src:{
            type:String,
            required:true
        },
        uploadUrl:{
            type:String,
            required:true
        }
    },
    methods:{
        //文件上传成功后调用
            handleAvatarSuccess(res, file) {
                this.chouse = 2
                this.src1 = res.result;
                this.$message({type: res.status, message: res.msg});
                this.fullLoading = false;
                this.$emit("loadFather",true);
            },
            //文件上传失败后调用
            handleAvatarError() {
                this.fullLoading = false;
            },
            //文件上传前置判断
            beforeAvatarUpload(file) {
                const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                this.$message.error('上传图片只能是 JPG / PNG 格式!');
                return false;
                }
                if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
                return false;
                }
                this.fullLoading = true;
                return isJPG && isLt2M;
            }
    },
    watch:{
        src:function(value,oldValue){
            this.chouse = 1
        }
    }
}
</script>

